package cn.finedo.aiability.service;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.logging.Logger;
import java.util.logging.Level;

import cn.finedo.aiability.exception.AiAbilityException;

public class AiAbilityHttpClient {

    private static final String DEF_CHATSET = "UTF-8";
    private static final String DEF_METHOD = "POST";
    private static final int DEF_CONN_TIMEOUT = 60000;
    private static final String DEF_CONTENT_TYPE = "application/json";
    private static final Logger logger = Logger.getLogger(AiAbilityHttpClient.class.getName());

    /**
     * @param url   请求链接地址
     * @param param 请求报文入参
     * @return
     * @throws AiAbilityException
     */
    public static String sendRequest(String url, String param) throws Exception {
        return sendRequest(url, param, null, null, DEF_CONN_TIMEOUT);
    }

    /**
     * @param url     请求链接地址
     * @param param   请求报文入参
     * @param timeout 超时时间
     * @return
     * @throws AiAbilityException
     */
    public static String sendRequest(String url, String param, Integer timeout) throws Exception {
        return sendRequest(url, param, null, null, timeout);
    }

    /**
     * @param url    请求链接地址
     * @param param  请求报文入参(json字符串)
     * @param appid  在EOP平台注册的appid
     * @param appKey 在EOP平台注册的appKey
     * @throws AiAbilityException
     */
    public static String sendRequest(String url, String param, String appid, String appKey) throws Exception {
        return sendRequest(url, param, appid, appKey, DEF_CONN_TIMEOUT);
    }

    /**
     * @param url     请求链接地址
     * @param param   请求报文入参(json字符串)
     * @param appid   在EOP平台注册的appid
     * @param appKey  在EOP平台注册的appKey
     * @param timeout 超时时间
     * @return
     * @throws Exception
     */
    public static String sendRequest(String url, String param, String appid, String appKey, Integer timeout) throws IOException {
        HttpURLConnection conn = null;
        OutputStreamWriter out = null;
        BufferedReader reader = null;
        StringBuilder result = new StringBuilder();
        try {
            URL urlstr = new URL(url);
            conn = (HttpURLConnection) urlstr.openConnection();
            logger.log(Level.INFO, "connected success !!");
            // Set request properties
            conn.setRequestMethod("POST"); // Assuming DEF_METHOD is "POST"
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8"); // Assuming these are the defaults
            conn.setRequestProperty("Accept", "application/json");
            conn.setConnectTimeout(timeout);
            conn.setReadTimeout(timeout);
            if (appid != null && !appid.isEmpty()) {
                conn.setRequestProperty("X-APP-ID", appid);
                conn.setRequestProperty("X-APP-KEY", appKey);
            }

            // Send request
            out = new OutputStreamWriter(conn.getOutputStream());
            out.write(param);
            out.flush();

            // Handle response
            int responseCode = conn.getResponseCode();
            logger.log(Level.INFO, "responseCode:" + responseCode);
            if (responseCode == HttpURLConnection.HTTP_OK) {
                InputStream in = conn.getInputStream();
                reader = new BufferedReader(new InputStreamReader(in, "UTF-8")); // Assuming DEF_CHATSET is "UTF-8"
                String line;
                while ((line = reader.readLine()) != null) {
                    result.append(line);
                }
            } else {
                InputStream errorStream = conn.getErrorStream();
                if (errorStream != null) {
                    // Read the error response to provide more context
                    BufferedReader errorReader = new BufferedReader(new InputStreamReader(errorStream, "UTF-8"));
                    String errorLine;
                    StringBuilder errorMessage = new StringBuilder();
                    while ((errorLine = errorReader.readLine()) != null) {
                        errorMessage.append(errorLine);
                    }
                    // Close the error stream reader
                    errorReader.close();

                    // Throw an exception with the detailed error message
                    throw new IOException("HTTP error occurred: " + responseCode + " errorMessage:" + errorMessage.toString());
                } else {
                    // If no error stream, throw with basic information
                    throw new IOException("HTTP error occurred: " + responseCode);
                }
            }
        } catch (IOException e) {
            logger.log(Level.SEVERE, "send message failed", e);
            // Wrap and throw with additional context if needed
            throw new IOException("Error sending HTTP request", e);
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    logger.log(Level.SEVERE, "关闭out失败", e);
                }
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    logger.log(Level.SEVERE, "关闭reader失败", e);
                }
            }
            if (conn != null) {
                conn.disconnect();
            }
        }

        // Return the result if successful
        return result.toString();
    }
}
